﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PaymentHelper.PaymentFlow;
using OnlineShop.Models;
using OnlineShop.Models.ViewModels;
using PaymentHelper.Core.RelatedObject;

namespace OnlineShop.Common
{
    public class MyOrderHandler:IOrderHandler
    {
        public MyOrderHandler()
        {            
        }

        /// <summary>
        /// Initialize a order of payment process
        /// </summary>
        /// <returns></returns>
        public PaymentHelper.Core.Order InitializeOrder()
        {
            var user = HttpContext.Current.Session["OSUser"];
            if (user == null)
                return null;

            var cart = HttpContext.Current.Session["Cart"];
            if (cart == null)
                return null;

            OSUser userCurrent = (OSUser)user;
            ShoppingCartModel cartModel = (ShoppingCartModel)cart;

            var order = new PaymentHelper.Core.Order();

            order.BillingAddress = userCurrent.UserInfoes.ToList()[0].ToAddress();
            order.CustomerCurrency = "USD";

            order.ListOrderItem = new List<OrderItem>();
            //Init List OrderItem
            foreach (var product in cartModel.Products)
            {
                order.ListOrderItem.Add(product.ToOrderItem());
            }

            return order;
        }
        
        /// <summary>
        /// Save the order of payment process
        /// </summary>
        /// <param name="order"></param>
        public void SaveOrder(PaymentHelper.Core.Order order)
        {
            Order newOrder = new Order();
            newOrder.OrderDate = DateTime.UtcNow;
            newOrder.OrderStatus = order.OrderStatus.ToString();
            newOrder.OrderToken = order.OrderId;
            newOrder.Ordertotal = (double)order.OrderTotal;

            var user = HttpContext.Current.Session["OSUser"];
            if (user != null)
                newOrder.UserId = ((OSUser)user).Id;

            foreach (var item in order.ListOrderItem)
            {
                var orderDetailItem = new OrderDetail()
                {
                    ProductId = Int32.Parse(item.Id),
                    Quantity = item.Quantiy,
                    UnitPrice = (double)item.Price,
                    Order = newOrder
                };
            }

            IOnlineShopRepository _shopReposity = new EFOnlineShopRepository();
            _shopReposity.AddOrder(newOrder);
            _shopReposity.CommitChanges();
        }
    }
}